<template>
  <div class="common-layout" style="height: 100%;">
    <div class="chat-window" :style="{ width: (socketService.caller || socketService.called) ? '50%' : '100%' }">
      <div class="top">
        房间号：{{ socketService.roomId }}
      </div>
      <div class="botoom">
        <div class="chat-content" ref="chatContent">
          <div class="chat-wrapper" v-for="item in socketService.messages" :key="item.id">
            <div class="chat-friend" v-if="item.id != socketService.uniqueId">
              <div class="chat-text" v-if="item.type === 'text'">
                <div v-html="item.content"></div>
              </div>
              <div class="chat-photo" v-else-if="item.type === 'photo'">
                <img :src="item.content" alt="Photo">
              </div>
              <div class="info-time">
                <span>{{ item.author }}</span>
              </div>
            </div>
            <div class="chat-me" v-else>
              <div class="chat-text" v-if="item.type === 'text'">
                <div v-html="item.content"></div>
              </div>
              <div class="chat-photo" v-else-if="item.type === 'photo'">
                <img :src="item.content" alt="Photo">
              </div>
              <div class="info-time">
                <span>{{ item.author }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="chatInputs">
          <div class="tool" style="display: flex;">
            <button class="video btn" @click="call">
              <img src="../../assets/svg/video.svg" alt="">
            </button>
            <button class="photo btn" ref="photoButton" @click="handlePhotoButtonClick">
              <img src="../../assets/svg/photo-choose.svg" alt="">
            </button>
            <button class="emoji btn" @click="chooseEmoji">
              <img src="../../assets/svg/emoji.svg" alt="">
            </button>
          </div>
          <editor-content :editor="editor" class="inputs" @keydown.enter.prevent="handleEnterKey" />
          <button class="send boxinput" @click="sendMessage()">发送</button>
          <div class="emojiPicker" v-if="showEmojiPicker">
            <Emoji @addEmoji="addEmoji" />
          </div>
        </div>
      </div>
    </div>
    <div v-if="(socketService.caller || socketService.called)" class="chat-video">
      <videoChat />
    </div>
  </div>
</template>

<script setup lang="ts">
import videoChat from '@/components/videoChat.vue';
import Emoji from '@/components/Emoji.vue';
import { useSocketStore } from '@/stores/socketStore';
import { onMounted, ref, onUpdated } from 'vue';
import Document from '@tiptap/extension-document'
import Dropcursor from '@tiptap/extension-dropcursor'
import Image from '@tiptap/extension-image'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import { Editor, EditorContent } from '@tiptap/vue-3';


// 接收传入的 roomId 作为 props
const props = defineProps<{
  username?: string  // 新增的 username 变量
}>()
const socketService = useSocketStore();
const showEmojiPicker = ref<boolean>(false);
const editor = ref<Editor>();
const photoButton = ref(null);
const chatContent = ref<HTMLDivElement | null>(null);

onMounted(() => {
  editor.value = new Editor({
    extensions: [Document,
      Paragraph,
      Text,
      Image,
      Dropcursor,],
    content: ``
  })
  socketService.socket.on('callRemote', () => {
    if (!socketService.caller) {// 如果不是发送方
      // console.log("收到视频请求");
      socketService.called = true; // 接听方
      socketService.calling = true;
    }
  })
  socketService.socket.on('sendMessage', async (message) => {
    if (socketService.uniqueId != message.id) {
      // console.log('收到消息')
      socketService.messages.push(message);
    }
  })
})

const handleEnterKey = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    event.preventDefault();
    sendMessage();
  }
};


// 发起方发起视频请求
const call = async () => {
  // console.log('发起视频');
  socketService.caller = true;
  socketService.calling = true;
};

// 发送消息到服务器
const sendMessage = () => {
  // 确保编辑器不为空并且有内容
  if (editor.value && editor.value.getHTML) {
    const content = editor.value.getHTML(); // 获取编辑器内容为HTML格式
    const author = props.username || ''; // 添加条件判断，如果props.username不存在，则将author赋值为空字符串

    const message = {
      id: socketService.uniqueId, // 假设 uniqueId() 是一个生成唯一ID的方法
      author: author, // 组件props中的用户名
      content: content, // 编辑器的内容
      type: 'text',
    };

    socketService.messages.push(message); // 假设 socketService.messages 是一个数组

    // 使用socket.io或类似方式将消息通过socket发送到服务器
    socketService.socket?.emit('sendMessage', { message, roomId: socketService.roomId });

    // 发送消息后重置编辑器内容
    editor.value.commands.setContent('');
  }
};


const chooseEmoji = () => {
  showEmojiPicker.value = true;
}

const addEmoji = (emoji: string) => {
  if (editor.value) {
    showEmojiPicker.value = false;

    // 获取编辑器的 HTML 内容
    const htmlContent = editor.value.getHTML();

    // 提取<p>标签中的内容
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlContent, 'text/html');
    const paragraphContent = doc.querySelector('p')!.textContent;

    // 将表情符号与<p>标签中的内容拼接
    const newContent = paragraphContent + emoji;

    // 更新编辑器的内容
    editor.value.commands.setContent('<p>' + newContent + '</p>');
  }
};


const handlePhotoButtonClick = () => {
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.accept = "image/*";

  fileInput.addEventListener("change", () => {
    const file = fileInput.files?.[0]!;
    const reader = new FileReader();

    reader.onload = (event) => {
      const base64Data = event.target?.result;
      sendPhotoMessage(base64Data);
    }

    reader.readAsDataURL(file);
  });

  fileInput.click();
}
const sendPhotoMessage = (data:any) => {
  const author = props.username || ''; // 添加条件判断，如果props.username不存在，则将author赋值为空字符串

  const message = {
    id: socketService.uniqueId,
    author: author,
    content: data,
    type: 'photo',
  }
  socketService.messages.push(message); // 假设 socketService.messages 是一个数组
  socketService.socket?.emit('sendMessage', { message, roomId: socketService.roomId })
}


const scrollToBottom = () => {
  chatContent.value?.scrollTo({ top: chatContent.value.scrollHeight, behavior: 'smooth' });
};

onUpdated(scrollToBottom);

</script>

<style>
.common-layout {
  height: 100%;
  display: flex;
}

.btn {
  margin-left: 5px;
  padding: 0;
  border: none;
  background: transparent;
}

.chatContent {
  height: 100%;
  display: flex;
}

.chat-video {
  height: 100%;
  width: 50%;
}

.chat-window {
  width: 100%;
  height: 100%;
  margin-left: 20px;
  position: relative;

  /* color: rgb(176, 178, 189); */
  .top {
    height: 7%;
    color: #fff;
  }

  .botoom {
    width: 100%;
    height: 93%;
    background-color: rgb(50, 54, 68);
    border-radius: 20px;
    padding: 20px;
    box-sizing: border-box;
    position: relative;

    .emojiItem {
      height: 30px;
      width: 30px;
    }

    .chat-content {
      width: 100%;
      height: 75%;
      overflow-y: scroll;
      padding: 20px;
      box-sizing: border-box;

      &::-webkit-scrollbar {
        width: 0;
        /* Safari,Chrome 隐藏滚动条 */
        height: 0;
        /* Safari,Chrome 隐藏滚动条 */
        display: none;
        /* 移动端、pad 上Safari，Chrome，隐藏滚动条 */
      }

      .chat-wrapper {
        position: relative;
        word-break: break-all;

        .chat-friend {
          width: 100%;
          float: left;
          margin-bottom: 20px;
          display: flex;
          flex-direction: column;
          justify-content: flex-start;
          align-items: flex-start;

          .chat-photo{
            max-width: 50%;
            img{
              width:100%;
              height: auto;
            }
          }

          .chat-text {
            max-width: 80%;
            padding: 20px;
            overflow-wrap: break-word;
            border-radius: 20px 20px 20px 5px;
            background-color: rgb(56, 60, 75);
            color: #fff;

            img {
              width: 30px;
              height: 30px;
            }

            &:hover {
              background-color: rgb(39, 42, 55);
            }
          }

          .chat-img {
            img {
              width: 100px;
              height: 100px;
            }
          }

          .info-time {
            margin: 10px 0;
            color: #fff;
            font-size: 14px;

            img {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              vertical-align: middle;
              margin-right: 10px;
            }

            span:last-child {
              color: rgb(101, 104, 115);
              margin-left: 10px;
              vertical-align: middle;
            }
          }
        }

        .chat-me {
          width: 100%;
          float: right;
          margin-bottom: 20px;
          position: relative;
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
          align-items: flex-end;

          .chat-photo{
            max-width: 50%;
            img{
              width:100%;
              height: auto;
            }
          }

          .chat-text {
            float: right;
            max-width: 90%;
            overflow-wrap: break-word;
            padding: 20px;
            border-radius: 20px 20px 5px 20px;
            background-color: rgb(29, 144, 245);
            color: #fff;

            img {
              width: 30px;
              height: 30px;
            }

            &:hover {
              background-color: rgb(26, 129, 219);
            }
          }

          .chat-img {
            img {
              max-width: 300px;
              max-height: 200px;
              border-radius: 10px;
            }
          }

          .info-time {
            margin: 10px 0;
            color: #fff;
            font-size: 14px;
            display: flex;
            justify-content: flex-end;

            img {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              vertical-align: middle;
              margin-left: 10px;
            }

            span {
              line-height: 30px;
            }

            span:first-child {
              color: rgb(101, 104, 115);
              margin-right: 10px;
              vertical-align: middle;
            }
          }
        }
      }
    }

    .chatInputs {
      width: 97%;
      position: absolute;
      bottom: 0;
      margin-bottom: 3%;
      margin-left: -1%;
      display: flex;
      flex-direction: column;

      /* 修改为垂直布局 */
      .tool {
        margin-left: 2%;

        * {
          margin-right: 3px;
        }

        .el-upload--picture-card {
          width: 20px;
          height: 20px;
          background-color: rgb(50, 54, 68);
          background: url(../../assets/svg/photo-choose.svg) center center / 100% 100%;
          border: none;
        }
      }

      .boxinput {
        width: 50px;
        height: 50px;
        background-color: rgb(66, 70, 86);
        border-radius: 15px;
        border: 1px solid rgb(80, 85, 103);
        position: relative;
        cursor: pointer;

        img {
          width: 30px;
          height: 30px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .emojiPicker {
        width: 480px;
        height: 160px;
        position: absolute;
        top: -160px;
        /* 其他样式属性... */
      }

      .emoji {
        transition: 0.3s;

        &:hover {
          background-color: rgb(46, 49, 61);
          border: 1px solid rgb(71, 73, 82);
        }
      }

      .inputs {
        flex-grow: 1;
        height: 120px;
        /* 自动高度 */
        background-color: rgb(66, 70, 86);
        border-radius: 15px;
        border: 2px solid rgb(34, 135, 225);
        padding: 10px;
        box-sizing: border-box;
        transition: 0.2s;
        font-size: 20px;
        color: #fff;
        font-weight: 100;
        margin: 0 20px;
        margin-bottom: -5%;
        outline: none;
        /* 移除焦点时的边框高亮效果 */

        &:focus {
          outline: none;
        }

        .tiptap.ProseMirror:focus {
          outline: none !important;
        }

        p {
          outline: none;
          max-height: 80px;
          overflow: auto;
          outline: none;
        }

        img {
          width: 30px;
          height: 30px;
        }
      }

      .send {
        background-color: rgb(29, 144, 245);
        height: 30px;
        border: 0;
        transition: 0.3s;
        box-shadow: 0px 0px 5px 0px rgba(0, 136, 255);
        margin-left: auto;
        /* margin-bottom: -2%; */
        /* 将左边距设为auto，使按钮靠右对齐 */
        margin-right: 5%;

        &:hover {
          box-shadow: 0px 0px 10px 0px rgba(0, 136, 255);
        }
      }

    }

  }
}
</style>
